﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Inventory_StockReceived : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            if (!IsPostBack)
                ResetForm();
        }
    }
    private void ResetForm()
    {
        try
        {
            //Cửa hàng chuyển
            string strShopID = string.Empty;
            ////if (Session["RoleID"] == null || Session["RoleID"].ToString() == "1")
            ////    strShopID = "0";
            ////else strShopID = Session["ShopID"].ToString();

            //strShopID = Session["ShopID"].ToString();
            //Utils.loadShopToCombo(cbFromShop, 1, 0);
            //Utils.loadShopToComboSearch(cbFromShopReceived, 1, 0, "");
            //if (strShopID == "0")
            //{
            //    Utils.loadShopToComboSearch(cbToShop, 1, 0);
            //    Utils.loadShopToComboSearch(cbToShopReceived, 1, 0, "");
            //}
            //else
            //{
            //    Utils.loadShopToComboSearch(cbToShop, 0, Convert.ToInt32(strShopID));
            //    Utils.loadShopToComboSearch(cbToShopReceived, 0,Convert.ToInt32(strShopID));
            //}
            //Cửa hàng nhận
            //Utils.loadShopToCombo(cbToShop, 0, 0, "S");

            loadProvince();
            RadPageView3.Selected = true;
            TabStrip1.SelectedIndex = 1;

            gvProduct.DataSource = new DataTable();
            gvProduct.DataBind();
            rdpTransferDate.SelectedDate = DateTime.Now.Date;
            
            rtpFromExportedDateSearch.SelectedDate = DateTime.Now.Date;
            rtpToExportedDateSearch.SelectedDate = DateTime.Now.Date;

            //Button
            
            btnInput.Enabled = false;
            //btnReject.Enabled = false;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReceived Page-loadForm:" + ex.Message);
        }
    }
    private void getDataSearchReceived()
    {
        ProStockReceived pro = new ProStockReceived();
        pro.strTransferOrderCodeSearch = Utils.KillChars(txtTransferWarehouseCodeReceived.Text.Trim());
        pro.strStartDate = Utils.KillChars(this.rtpFromExportedDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromExportedDateSearch.SelectedDate));
        pro.strEndDate = Utils.KillChars(this.rtpToExportedDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToExportedDateSearch.SelectedDate));
        pro.strStatusSearch = Utils.KillChars(cbStatusReceived.SelectedValue.Trim().ToString());
        pro.iToShopIDSearch = Convert.ToInt32(Utils.KillChars(cbToShopReceived.SelectedValue.Trim().ToString() == "0" ? "-1" : cbToShopReceived.SelectedValue.Trim().ToString()));
        pro.iFromShopIDSearch = Convert.ToInt32(Utils.KillChars(cbFromShopReceived.SelectedValue.Trim().ToString() == "0" ? "-1" : cbFromShopReceived.SelectedValue.Trim().ToString()));
        pro.iProvinceIDSearch = Convert.ToInt32(Utils.KillChars(cbProvinceSearch.SelectedValue.Trim().ToString() == "0" ? "-1" : cbProvinceSearch.SelectedValue.Trim().ToString()));
        loadData(pro);
    }
    private void loadProvince()
    {
        try
        {
            //Load tinh thanh 
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
            int isProvinceAll = (ProvinceID == 0 ? 1 : 0);
            Utils.loadLocationSearch(cbProvinceSearch, 0, isProvinceAll, ProvinceID);//Search
            loadShop(-1, ProvinceID);


        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-LoadProvince:" + ex.Message);
        }
    }
    private DataTable DTTransferWarehouseDetail(int ID = 0)
    {
        //DataTable dt = null;
        try
        {
            db = new DBDataContext();
            var dtPurchaseOrderDetail = (from a in db.TransferWarehouseDetails
                                         join b in db.Products on a.ProductID equals b.ID
                                         where a.TransferWarehouseID == ID && a.Status == 'A' && b.Status == 'A'
                                         select new
                                         {
                                             ProductID = b.ID + "|" + a.PackType,
                                             ProductName = b.ProductCode + "-" + b.ProductName + (a.PackType == 0 ? "" : " (" + a.PackType + " kg)"),
                                             PurchasePrice = Convert.ToDouble(a.PurchasePrice),
                                             Amount = Convert.ToDouble(a.Amount),
                                             Quantity = Convert.ToInt32(a.Quantity),
                                             Weight = a.PackType == 0 ? a.Quantity : (a.PackType * a.Quantity)
                                         }).ToList();


            return dtPurchaseOrderDetail.ToDataTable();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockRecieved Page-deletePurchaseOrderDetail-Username:" + Session["Username"].ToString() + "-TransferWarehouseID:" + ID.ToString()+ "-Error:" + ex.Message.ToString());
            return new DataTable();
        }

    }
    private void loadData(ProStockReceived pro)
    {
        try
        {
            int PageNumber = gvReceived.CurrentPageIndex + 1;
            int PageSize = gvReceived.PageSize;

            helper = new DatabaseHelper();

            System.Data.Common.DbParameter TransferType = helper.Parameter;
            TransferType.ParameterName = "TransferType";
            TransferType.DbType = DbType.Int32;
            TransferType.Value = 2;
            helper.AddParameter(TransferType);

            System.Data.Common.DbParameter paramPurchaseOrderID = helper.Parameter;
            paramPurchaseOrderID.ParameterName = "TransferWarehouseID";
            paramPurchaseOrderID.DbType = DbType.Int32;
            paramPurchaseOrderID.Value = -1;
            helper.AddParameter(paramPurchaseOrderID);

            System.Data.Common.DbParameter paramFromShopID = helper.Parameter;
            paramFromShopID.ParameterName = "FromShopID";
            paramFromShopID.DbType = DbType.Int32;
            paramFromShopID.Value = pro.iFromShopIDSearch;
            helper.AddParameter(paramFromShopID);

            System.Data.Common.DbParameter paramToShopID = helper.Parameter;
            paramToShopID.ParameterName = "ToShopID";
            paramToShopID.DbType = DbType.Int32;
            paramToShopID.Value = pro.iToShopIDSearch;
            helper.AddParameter(paramToShopID);

            System.Data.Common.DbParameter ProvinceID = helper.Parameter;
            ProvinceID.ParameterName = "ProvinceID";
            ProvinceID.DbType = DbType.Int32;
            ProvinceID.Value = pro.iProvinceIDSearch;
            helper.AddParameter(ProvinceID);

            System.Data.Common.DbParameter paramStatus = helper.Parameter;
            paramStatus.ParameterName = "Status";
            paramStatus.DbType = DbType.String;
            paramStatus.Value = pro.strStatusSearch;
            helper.AddParameter(paramStatus);


            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "ProductType";
            paramType.DbType = DbType.String;
            paramType.Value = pro.strTypeSearch;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = pro.strStartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = pro.strEndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetTransferWarehouse", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                gvReceived.Height = 250;
                gvReceived.ClientSettings.Scrolling.AllowScroll = true;
                gvReceived.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvReceived.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}",dt.Rows[0]["TotalRows"]);
                gvReceived.DataSource = dt;
            }
            else
            {
                gvReceived.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
            }

            //gvReceived.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockRecieved Page-loadData-Username:" + Session["Username"].ToString() +"-Error:" + ex.Message);
        }
    }
    private void fillData(ProStockReceived pro)
    {
        try
        {
            txtTransferWarehouseCode.Text = pro.strTransferOrderCode;
            txtFromShop.Text = pro.strFromShopName;
            txtToShop.Text = pro.strToShopName;
            cbType.SelectedValue = pro.strType;
            rdpTransferDate.SelectedDate = pro.dateTimeTransferDate;
            txtStatus.Text = pro.strStatusName;
            //divTotalAmount.InnerText = "Tổng tiền: " + String.Format("{0:#,#.##}", pro.dTotalAmount);
            //divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", pro.dTotalWeight);
            //divGetTotalWeight.InnerText = pro.dTotalWeight.ToString();
            //divGetTotalAmount.InnerText = pro.dTotalAmount.ToString();
            txtRemark.Text = pro.strRemark;
            txtExportedEmployee.Text = pro.strExportedEmployee;
            txtExportedDate.Text = pro.strExportedDate;
            txtDeliveryPerson.Text = pro.strDeliveryPerson;
            //txtLastUpdatedBy.Text = pro.LastUpdatedBy;
            //txtLastUpdatedDateTime.Text = pro.LastUpdatedDateTime;

            RadPageView1.Selected = true;
            TabStrip1.SelectedIndex = 0;
            if (ViewState["TransferWarehouseID"] != null)
            {
                DataTable dt = DTTransferWarehouseDetail(Convert.ToInt32(ViewState["TransferWarehouseID"]));
                if (dt.Rows.Count > 0)
                {
                    ViewState["TBLTransferWarehouseDetail"] = dt;
                    Double iTotalQuantity = Convert.ToInt32(dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Quantity"])));
                    divTotalQuantity.InnerHtml = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                    divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                    divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " kg";
                    Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                    divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                    divGetTotalAmount.InnerText = iTotalAmount.ToString();
                }
                else
                {
                    divTotalQuantity.InnerText = "Tổng số lượng: 0";
                    divTotalWeight.InnerText = "Tổng trọng lượng: 0 kg";
                    divGetTotalQuantity.InnerText = "";
                    divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                    divGetTotalAmount.InnerText = "";
                }
                if (pro.strType == "P")
                    divTotalWeight.Visible = false;
                gvProduct.DataSource = dt;
                gvProduct.DataBind();
                gvProduct.Enabled = false;
                div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
            }
            SetStatus(pro.strStatus);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReceived Page-fillData-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message);
        }
    }
    private DataTable createTable()
    {
        DataTable dt = null;
        try
        {
            if (ViewState["TBLTransferWarehouseDetail"] == null)
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.Int32"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("PurchasePrice", System.Type.GetType("System.Double"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Double"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));
                //dt.Columns.Add("Delete");
            }
            else dt = (DataTable)ViewState["TBLTransferWarehouseDetail"];
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReceived Page-createTable-Username: " + Session["UserName"].ToString() + "- Error:" + ex.Message.ToString());
        }
        return dt;
    }
    private void SetStatus(string strStatus)
    {
        if (strStatus == "T"  || strStatus == "F")//Da Xuat kho
        {
            /**
             * N: Tạo mới, C: hủy bỏ, T: Đã xuất kho, I: Xóa,  F: Hoàn tất(Xác nhận)
             * 
             */
            //Button            
            btnInput.Enabled = true;
            //btnReject.Enabled = true;
            txtDeliveryPerson.ReadOnly = true;
            //Combo
            cbType.Enabled = false;
            //cbToShop.Enabled = false;
            //cbFromShop.Enabled = false;
            if (strStatus == "F")
            {
                btnInput.Enabled = false;
                //btnReject.Enabled = false;
                rdpTransferDate.Enabled = false;
            }
        } 
    }
    private bool save(ProStockReceived pro)
    {
        db = new DBDataContext();
        try
        {
            if (ViewState["TransferWarehouseID"] != null)
            {
                TransferWarehouse obj = db.TransferWarehouses.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["TransferWarehouseID"]));
                if (obj.Status.ToString() == "T")//Neu trinh trang Xuat Kho thi moi Xác nhận
                {
                    using (var transation = new TransactionScope())
                    {
                        try
                        {
                            string strUserName = Session["Username"].ToString();
                            obj.Status = Convert.ToChar(pro.strStatus);
                            obj.ImportedEmployee = strUserName;
                            obj.ImportedDate = DateTime.Now;
                            obj.LastUpdatedBy = strUserName;
                            obj.LastUpdatedDateTime = DateTime.Now;
                            obj.Remark = pro.strRemark;
                            int iProductID = 0;
                            int iPackType = 0;
                            int? iQuantity = 0;
                            double? dPurchasePrice = 0;
                            List<Warehouse> listWarehouseInsert = new List<Warehouse>();
                            List<Warehouse> listWarehouseUpdate = new List<Warehouse>();
                            List<Warehouse> listWarehouseSub = new List<Warehouse>();//List tru kho
                            //Tru kho di kho di
                            var listDetailSubtract = (from a in db.TransferWarehouseDetails where a.Status == 'A' && a.TransferWarehouseID == Convert.ToInt32(ViewState["TransferWarehouseID"]) select a).ToList();
                            foreach (var a in listDetailSubtract)
                            {
                                iProductID = Convert.ToInt32(a.ProductID);
                                iPackType = Convert.ToInt32(a.PackType);
                                iQuantity = a.Quantity;
                                dPurchasePrice = a.PurchasePrice;
                                //Tru kho xuat
                                var subtractWarehouse = (from c in db.Warehouses
                                                         where c.ProductID == iProductID
                                                               && c.ShopID == obj.FromShopID
                                                               && c.PackType == iPackType
                                                               && c.Status == 'A'
                                                         select c).FirstOrDefault();
                                if (subtractWarehouse != null)
                                {
                                    subtractWarehouse.Quantity = subtractWarehouse.Quantity - iQuantity;
                                    subtractWarehouse.RefCode = obj.TransferWarehouseCode;
                                    subtractWarehouse.RefType = "Xuất kho luân chuyển";
                                    subtractWarehouse.Remark = "TransferWarehouse";
                                    if (subtractWarehouse.Quantity <= 0)
                                    {
                                        subtractWarehouse.PurchasePrice = 0;
                                    }
                                    listWarehouseSub.Add(subtractWarehouse);
                                    //db.SubmitChanges();
                                }
                                //Caculate: //Cong kho den
                                var checkExistsProduct = (from c in db.Warehouses
                                                          where c.ProductID == iProductID
                                                                && c.ShopID == obj.ToShopID
                                                                && c.PackType == iPackType
                                                                && c.Status == 'A'
                                                          select c).FirstOrDefault();
                                if (checkExistsProduct == null)//ProductID chua ton tai thi Insert Warehouse
                                {
                                    Warehouse objWarehouse = new Warehouse();
                                    objWarehouse.ProductID = iProductID;
                                    objWarehouse.ShopID = pro.iToShopID;
                                    objWarehouse.PackType = iPackType;
                                    objWarehouse.PurchasePrice = dPurchasePrice;
                                    objWarehouse.Quantity = iQuantity;
                                    objWarehouse.CreatedBy = strUserName;
                                    objWarehouse.CreatedDateTime = DateTime.Now;
                                    objWarehouse.LastUpdatedBy = strUserName;
                                    objWarehouse.LastUpdatedDateTime = DateTime.Now;
                                    objWarehouse.RefCode = obj.TransferWarehouseCode;
                                    objWarehouse.RefType = "Nhập kho luân chuyển";
                                    objWarehouse.Remark = "TransferWarehouse";
                                    objWarehouse.Status = 'A';
                                    listWarehouseInsert.Add(objWarehouse);
                                    //db.Insert<Warehouse>(objWarehouse);
                                    //db.SubmitChanges();
                                }
                                else //ProductID  ton tai thi Update Quantity, PurchasePrice: Warehouse
                                {
                                    //Caculate: Quantity
                                    checkExistsProduct.Quantity = checkExistsProduct.Quantity + iQuantity;
                                    if (checkExistsProduct.Quantity <= 0)// so luong = 0
                                    {
                                        dPurchasePrice = 0;
                                    }
                                    else
                                    {
                                        double dOldPurchasePrice = Convert.ToDouble(checkExistsProduct.PurchasePrice);
                                        checkExistsProduct.PurchasePrice = dOldPurchasePrice == 0 ? dPurchasePrice : (dOldPurchasePrice + dPurchasePrice) / 2;
                                    }
                                    listWarehouseUpdate.Add(checkExistsProduct);
                                    //db.SubmitChanges();
                                }

                            }
                            //Tru kho di
                            if (listWarehouseSub.Count > 0)
                            {
                                db.Update<Warehouse>(listWarehouseSub);
                            }
                            //Cong kho den Warehouse
                            if (listWarehouseInsert.Count > 0)
                            {
                                db.Insert<Warehouse>(listWarehouseInsert);
                            }
                            if (listWarehouseUpdate.Count > 0)
                            {
                                db.Update<Warehouse>(listWarehouseUpdate);
                            }
                            db.SubmitChanges();
                            transation.Complete();
                        }
                        catch (Exception ex)
                        {
                            ControlUtil.LogError("StockReceived Page-Save-Transation-Status-F-TransferWarehouseID:" + ViewState["TransferWarehouseID"].ToString() + "-Username:" + Session["UserName"].ToString() + "-Error:"  + ex.Message);
                            transation.Dispose();
                            //ViewState["PurchaseOrderID"] = null;
                            return false;
                        }
                    }
                }
            }
            db.Connection.Close();
            return true;
            
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReceived Page-Save-Username:" + Session["UserName"].ToString() + "-Error:" + ex.Message);
            return false;
        }
        finally
        {
            db.Connection.Close();
        }
    }
    private void loadShop(int ProvinceID = -1, int ProvinceIDSearch = -1)
    {
        try
        {
            //load Shop
            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToComboSearch(cbToShopReceived, isShopAll, ProvinceIDSearch, ShopID, "");
            
            Utils.loadShopToComboSearch(cbFromShopReceived, 1, 0, "");

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-loadShop-Username:" + Session["UserName"].ToString() + "-Error:" + ex.Message);
        }
    }
    private List<TransferWarehouseDetail> insertTransferWarsehouseDetail(int iTransferWarsehouseDetail = 0)
    {
        try
        {
            List<TransferWarehouseDetail> listDetail = new List<TransferWarehouseDetail>();
            foreach (GridDataItem item in gvProduct.Items)
            {
                TransferWarehouseDetail soDetail = new TransferWarehouseDetail();
                soDetail.TransferWarehouseID = iTransferWarsehouseDetail;
                soDetail.ProductID = int.Parse(Utils.KillChars(item["ProductID"].Text.Trim()));
                string strPurchasePrice = Utils.KillChars(((Label)(item.FindControl("lblPurchasePrice"))).Text.Trim().Replace(",", ""));
                soDetail.PurchasePrice = Convert.ToDouble(strPurchasePrice == "" ? "0" : strPurchasePrice);
                string strWeight = Utils.KillChars(((Label)(item.FindControl("lblWeight"))).Text.Trim().Replace(",", ""));
                soDetail.Quantity = Convert.ToInt32(strWeight == "" ? "0" : strWeight);
                string strAmount = Utils.KillChars(((Label)(item.FindControl("lblAmount"))).Text.Trim().Replace(",", ""));
                soDetail.Amount = Convert.ToDouble(strAmount == "" ? "0" : strAmount);
                soDetail.CreatedBy = Session["UserName"].ToString();
                soDetail.LastUpdatedBy = Session["UserName"].ToString();
                soDetail.CreatedDateTime = DateTime.Now;
                soDetail.LastUpdatedDateTime = DateTime.Now;
                soDetail.Status = 'A';
                listDetail.Add(soDetail);
            }
            return listDetail;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReceived Page-insertPurchaseOrderDetail-Username:" + Session["UserName"].ToString() + "-TransferWarehouseID:" + iTransferWarsehouseDetail.ToString() + "-Error:" + ex.Message);
            return null;
        }
    }   
    protected void gvReceived_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();
                ProStockReceived pro = new ProStockReceived();

                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView1.Selected = true;
                        TabStrip1.SelectedIndex = 0;
                        System.Data.Common.DbParameter paramNewsID = helper.Parameter;
                        paramNewsID.ParameterName = "TransferWarehouseID";
                        paramNewsID.DbType = DbType.Int32;
                        paramNewsID.Value = ID;
                        helper.AddParameter(paramNewsID);
                        DataTable dt = helper.ExecuteDataTable("Admin_GetTransferWarehouse", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                        if (dt.Rows.Count > 0)
                        {
                            pro.strTransferOrderCode = dt.Rows[0]["TransferWarehouseCode"].ToString();
                            pro.strFromShopName = dt.Rows[0]["FromShopName"].ToString();
                            pro.strToShopName = dt.Rows[0]["ToShopName"].ToString();
                            ViewState["FromShopID"] = Convert.ToInt32(dt.Rows[0]["FromShopID"].ToString());
                            ViewState["ToShopID"] = Convert.ToInt32(dt.Rows[0]["ToShopID"].ToString());
                            pro.iFromShopID = Convert.ToInt32(dt.Rows[0]["FromShopID"].ToString());
                            pro.iToShopID = Convert.ToInt32(dt.Rows[0]["ToShopID"].ToString());
                            pro.strType = dt.Rows[0]["ProductType"].ToString();
                            pro.strStatus = dt.Rows[0]["Status"].ToString();
                            pro.dateTimeTransferDate = Convert.ToDateTime(dt.Rows[0]["TransferDate"].ToString());
                            pro.strStatusName = dt.Rows[0]["StatusName"].ToString();
                            pro.dTotalAmount = Convert.ToDouble(dt.Rows[0]["TotalAmount"].ToString());
                            pro.iTotalQuanity = Convert.ToInt32(dt.Rows[0]["TotalQuantity"].ToString());
                            pro.strDeliveryPerson = dt.Rows[0]["DeliveryPerson"].ToString();
                            pro.strRemark = dt.Rows[0]["Remark"].ToString();
                            pro.strExportedEmployee = dt.Rows[0]["ExportedEmployee"].ToString();
                            pro.strExportedDate = dt.Rows[0]["ExportedDate"].ToString();
                            pro.LastUpdatedBy = dt.Rows[0]["LastUpdatedBy"].ToString();
                            pro.LastUpdatedDateTime = dt.Rows[0]["LastUpdatedDateTime"].ToString();
                            ViewState["TransferWarehouseID"] = ID;
                            fillData(pro);

                        }
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("StockReceived Page-gvReceived_ItemCommand-EditItem-Username:" + Session["Username"].ToString() + "-TransferWarehouseID:" +ID.ToString()+"-Error:"+ ex.Message);
                    }
                }
                //else if (commandName == "DeleteItem")
                //{
                //    try
                //    {
                //        delete(ID);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                //        gvData.Rebind();
                //    }
                //    catch (Exception ex)
                //    {
                //        ControlUtil.LogError("StockReceived Page-gvData_ItemCommand-DeleteItem:" + ex.Message);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                //    }
                //}
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockReceived Page-gvData_ItemCommand-Username:" + Session["Username"].ToString() +"-Error:"+ ex.Message);
            }
        }
    }
    protected void gvReceived_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            //Ham phan trang: Paging
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 2;
                gvReceived.Height = 250;
                gvReceived.Visible = true;
                getDataSearchReceived();
            }
            else
            {
                gvReceived.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReceived Page-gvReceived_ItemCommand-Username:" + Session["Username"].ToString() +"-Error" + ex.Message);
        }
    }
    protected void cbProvince_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (!cbProvinceSearch.SelectedValue.Trim().Equals("0") && !string.IsNullOrEmpty(cbProvinceSearch.SelectedValue.Trim()))
            loadShop(-1, Convert.ToInt32(cbProvinceSearch.SelectedValue.Trim()));
    }

    #region Properties
    public class ProStockReceived
    {
        public string strTransferOrderCode { get; set; }
        public DateTime dateTimeTransferDate { get; set; }
        public string strRemark { get; set; }
        public string strType { get; set; }
        public int? iFromShopID { get; set; }
        public int? iToShopID { get; set; }
        public string strFromShopName { get; set; }
        public string strToShopName { get; set; }
        public string strDeliveryPerson { get; set; }
        public string strExportedEmployee { get; set; }
        public string ImportedEmployee { get; set; }
        public string strExportedDate { get; set; }
        public string LastUpdatedBy { get; set; }
        public string LastUpdatedDateTime { get; set; }
        public int? iOrderNumber { get; set; }
        public string strStatus { get; set; }
        public string strStatusName { get; set; }
        public int? iPurchaseOrderPrice { get; set; }
        public int? iAmount { get; set; }
        public double? dTotalAmount { get; set; }
        public int? iTotalQuanity { get; set; }
        public string strStartDate { get; set; }
        public string strEndDate { get; set; }
        public string strTypeSearch { get; set; }
        public int? iFromShopIDSearch { get; set; }
        public int? iToShopIDSearch { get; set; }
        public int? iProvinceIDSearch { get; set; }
        public string strTransferOrderCodeSearch { get; set; }
        public string strStatusSearch { get; set; }
    }
    #endregion End Properties
   
    protected void btnSearchReceived_Click(object sender, EventArgs e)
    {
        getDataSearchReceived();
        gvReceived.DataBind();
    }
    protected void btnInput_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                db = new DBDataContext();
                //Check san pham con ton kho hay khong
                int iProductID = 0;
                int iPackType = 0;
                if (ViewState["TBLTransferWarehouseDetail"] != null)
                {
                    string strFromShop = ViewState["FromShopID"].ToString();
                    DataTable dt = (DataTable)ViewState["TBLTransferWarehouseDetail"];
                    foreach (DataRow DRow in dt.Rows)
                    {
                        string[] arr = Utils.KillChars(DRow["ProductID"].ToString()).Split('|');

                        iProductID = Convert.ToInt32(arr[0]);
                        iPackType = Convert.ToInt32(arr[1]);
                        string strQuantity = Utils.KillChars(DRow["Quantity"].ToString().Replace(",", ""));
                        string strProductName = Utils.KillChars(DRow["ProductName"].ToString().Replace(",", ""));
                        var subtractWarehouse = (from c in db.Warehouses
                                                 where c.ProductID == iProductID
                                                       && c.ShopID == Convert.ToInt32(strFromShop == "" ? "-1" : strFromShop)
                                                       && c.PackType == iPackType
                                                       && c.Status == 'A'
                                                       && c.Quantity >= Convert.ToInt32(strQuantity)
                                                 select c).FirstOrDefault();
                        if (subtractWarehouse == null)
                        {
                            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng " + strProductName + " chuyển đã vượt quá số lượng của kho!");
                            //cbProduct.Focus();
                            return;
                        }
                    }
                }

                //Xác nhận
                ProStockReceived pro = new ProStockReceived();
                pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
                pro.strStatus = "F";
                pro.iToShopID = Convert.ToInt32(ViewState["ToShopID"]);
                pro.iFromShopID = Convert.ToInt32(ViewState["FromShopID"]);
                if (save(pro))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xác nhận thành công!");
                    SetStatus("F");
                    RadPageView1.Selected = true;
                    TabStrip1.SelectedIndex = 0;
                }
                else JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xác nhận không thành công, vui lòng kiểm tra dữ liệu!");
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockReceived Page-btnInput_Click-Username:" + Session["Username"].ToString() +"-Error:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xác nhận không thành công, vui lòng kiểm tra dữ liệu!");
            }
        }
    }
    //protected void btnReject_Click(object sender, EventArgs e)
    //{
    //    if (Session["Username"] != null)
    //    {
    //        try
    //        {
    //            ProStockReceived pro = new ProStockReceived();
    //            pro.strStatus = "R";
    //            pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
    //            pro.iFromShopID = Convert.ToInt32(cbFromShop.SelectedValue);
    //            if (save(pro))
    //            {
    //                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Từ chối nhập kho thành công!");
    //                SetStatus("R");
    //            }
    //            else JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Từ chối nhập kho không thành công, vui lòng kiểm tra dữ liệu!");
    //        }
    //        catch (Exception ex)
    //        {
    //            ControlUtil.LogError("StockReceived Page-btnReject_Click:" + ex.Message.ToString());
    //            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Từ chối nhập kho không thành công, vui lòng kiểm tra dữ liệu!");
    //        }
    //    }
    //}
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        getDataSearchReceived();
        gvReceived.DataBind();
    }
}